package com.den4.jynform;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.tanukisoftware.wrapper.WrapperListener;
import org.tanukisoftware.wrapper.WrapperManager;

/**
 * Fires up the Aquent Monitor service.
 * @author abargnesi
 */
public class StartMonitor implements WrapperListener {
    private Scheduler defaultScheduler;
    
    public void controlEvent(int event) {
        if (WrapperManager.isControlledByNativeWrapper()) {
            // The Wrapper will take care of this event
        } else {
            // We are not being controlled by the Wrapper, so
            //  handle the event ourselves.
            if ((event == WrapperManager.WRAPPER_CTRL_C_EVENT) ||
                (event == WrapperManager.WRAPPER_CTRL_CLOSE_EVENT) ||
                (event == WrapperManager.WRAPPER_CTRL_SHUTDOWN_EVENT)){
                WrapperManager.stop(0);
            }
        }
    }

    public Integer start(String[] args) {
        //Read 'config.properties'.
        File configFile = new File("config.properties");
        if(!configFile.exists()) {
            //Fail, because config.properties does not exist and the system can't start
            //without it :).
            System.out.println("Configuration file does not exist.");
            System.exit(900);
        }
        
        Properties configProps = new Properties();
        try {
            configProps.load(new FileInputStream(configFile));
        } catch (Exception e) {
            System.out.println("Problem reading properties from config.properties file.");
            e.printStackTrace();
            System.exit(901);
        }
        
        //TODO process properties file.
        
        return null;
    }

    /**
     * Pause all jobs and shutdown.
     */
    public int stop(int exitCode) {
        try {
            defaultScheduler.pauseAll();
            defaultScheduler.shutdown();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return exitCode;
    }
    
    public static void main(String[] args) {
        WrapperManager.start(new StartMonitor(), args);
    }
}
